<template>
  <el-dialog
    v-model="visible"
    :close-on-click-modal="false"
    title="关联设备"
    draggable
    width="700px"
  >
    <el-form :model="form" ref="formRef" :inline="true" label-position="left" label-width="auto">
      <el-form-item label="关联设备" prop="machineType">
        <el-select v-model="form.machineType" placeholder="请选择" clearable>
          <el-option
            v-for="item in machineTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="machineId">
        <ApiSelect
          v-model="form.machineId"
          :params="{ machineType: form.machineType }"
          :api="selectState.enterpriseUserMachine.api"
          :valueField="selectState.enterpriseUserMachine.valueField"
          :labelField="selectState.enterpriseUserMachine.labelField"
          clearable
          @change="change"
        />
      </el-form-item>
    </el-form>
    <div style="display: flex; justify-content: flex-end">
      <el-button @click="visible = false">上一步</el-button>
      <el-button type="primary" @click="confirm">审核通过</el-button>
    </div>
  </el-dialog>
</template>
<script setup>
import { listDataApi } from '@/api/system/dict/data'
import { useOrganApiConfig } from '@/hooks/service'

const selectState = useOrganApiConfig()
const visible = ref(false)
const form = ref({
  machineType: '3',
  machineId: null
})
const machineTypeList = ref()
const formRef = ref()
function init() {
  listDataApi({ dictType: 'device_type' }).then((res) => {
    console.log(res)
    machineTypeList.value = res.rows.map((item) => {
      return {
        value: item.dictValue,
        label: item.dictLabel
      }
    })
  })
  visible.value = true
}
function confirm() {
  console.log(form.value)
  formRef.value.validate((valid) => {
    if (valid) {
      emits('modifyData', form.value)
      visible.value = false
    }
  })
}
watch(
  () => visible.value,
  () => {
    visible.value ? '' : (form.value = { machineType: '3', machineId: null })
  }
)
/**下拉框选中的设备id、设备名称 */
function change(ev, option) {
  form.value.machineName = option.machineName
}

const emits = defineEmits(['modifyData'])
defineExpose({
  init
})
</script>
<style lang="scss" scoped></style>
